package com.adgroup.doremon_ad;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import model.User;
import model.Video;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import quick.action.ActionItem;
import quick.action.QuickAction;
import util.Config;
import util.Utility;
import adapter.AdapterSearchVideo;
import adapter.AdapterSearchVideo.IOnClickItemSearchVideo;
import adapter.JsonParse;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.adgroup.doremon_ad.R;
import com.adgroup.doremon_ad.MainActivity.AsynGetLinkYouTube;
import com.adgroup.doremon_ad.MainActivity.AsynRemoveVideo;
import com.facebook.FacebookException;
import com.facebook.Request;
import com.facebook.Request.GraphUserCallback;
import com.facebook.Response;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Util;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.model.GraphUser;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;

import database.Database;

public class SearchActiviy extends SherlockActivity implements IOnClickItemSearchVideo{

	private ActionBar mActionBar;
	private Facebook facebook;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		/*MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_detailchart, menu);*/
		return super.onCreateOptionsMenu(menu);
		
	}
	
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		
		case android.R.id.home:
			Utility.HideKeyboard(getApplicationContext(), et);
			finish();
			break;
		case R.id.menuShareFacebook: 			
			User u = new Database(SearchActiviy.this).getUser();
			if(u!=null && u.getType().equalsIgnoreCase("1")){				
				SharedPreferences share = getSharedPreferences("sharefilmllk",
					      MODE_PRIVATE);
					    SharedPreferences.Editor editor = share.edit();
					   
				//SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(DetailChartActivity.this);
				facebook.setAccessToken(share.getString("access", "0"));
				long expied = share.getLong("access_expires", 0);
				facebook.setAccessExpires(expied);
				 
				if(facebook.getSession()!=null){ 
					publishFeedDialog(null);
				}
				else{
					loginFacebook();
				}
			}
			else{
				loginFacebook();
			} 
			break;
		default:
			break;  
		}
		return super.onOptionsItemSelected(item);
	}
	private class IDRequestListener implements RequestListener {

        @Override
        public void onComplete(String response, Object state) {
                try {
                        
                        JSONObject json = Util.parseJson(response);

                        final String id = json.getString("id");
                        final String name = json.getString("name");
                        String access = facebook.getSession().getAccessToken();
						Date d = facebook.getSession().getExpirationDate();
						long milliseconds = d.getTime();
						SharedPreferences share = getSharedPreferences(
								"sharefilmllk", MODE_PRIVATE);
						SharedPreferences.Editor editor = share
								.edit();

						editor.putLong("access_expires",
								milliseconds);
						editor.putString("access", access);

						String email = json.getString("email");
						String birthday = "2012-12-12";//json.getString("birthday");
						final String nickname = json.getString("name");
						String username = json.getString("username");
						editor.putString("username", nickname);
						editor.commit();
						String gender = json.getString("gender");
						if(gender.toLowerCase().equalsIgnoreCase("male")){
							gender = "1";
						}
						else if(gender.toLowerCase().equalsIgnoreCase("female")){
							gender = "0";
						}
						String avatar = json.getString("id");
						avatar = "http://graph.facebook.com/"+avatar+"/picture";
						runOnUiThread(new Runnable() {
							public void run() {
								AlertDialog.Builder alert = new AlertDialog.Builder(SearchActiviy.this);
								alert.setTitle(getResources().getString(R.string.welcomeuser1)+" "+nickname);
								alert.setMessage(getResources().getString(R.string.share_facebook_alert));
								alert.setNeutralButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										publishFeedDialog(null);
									}
								});
								alert.setPositiveButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
									}
								});
								
								alert.show();
							}
						});
						//String[] params = new String[] {email,username,birthday,nickname,gender,avatar,Config.typeFacebook,"1","gcmid"};//1: facebook
					//	new AsyntaskLoginWithSocial().execute(params);
							
                } catch (JSONException e) {
                      
                } catch (FacebookError e) {
                      
                }
        }

        @Override
        public void onIOException(IOException e, Object state) {
                
        }

        @Override
        public void onFileNotFoundException(FileNotFoundException e,
                        Object state) {
               
        }

        @Override
        public void onMalformedURLException(MalformedURLException e,
                        Object state) {
                
        }

        @Override
        public void onFacebookError(FacebookError e, Object state) {
                
        }

}
	@SuppressWarnings("deprecation")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		facebook.authorizeCallback(requestCode, resultCode, data);
		if(requestCode==Config.LIKE_TO_LOGIN && resultCode==RESULT_OK){//register then login
			likeVideo();
		}
	}
	private class LoginDialogListener implements DialogListener { 
		  
        @SuppressWarnings("deprecation")
		@Override
        public void onComplete(Bundle values) {       
                mAsyncRunner.request("me", new IDRequestListener());
        }

        @Override
        public void onFacebookError(FacebookError e) {
        }

        @Override
        public void onError(DialogError e) {
        }

        @Override
        public void onCancel() {
        }
}
	@SuppressWarnings("deprecation")
	private void loginFacebook() {
		facebook = new Facebook(getResources().getString(R.string.facebook_app_id));
        mAsyncRunner = new AsyncFacebookRunner(facebook);
        facebook.authorize(SearchActiviy.this, PERMS, new LoginDialogListener());
		/*facebook.authorize(SearchActiviy.this,new String[]{"email","publish_stream","offline_access"}, new DialogListener() {
			
			@Override
			public void onFacebookError(FacebookError e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onError(DialogError e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onComplete(Bundle values) {
				Request.executeMeRequestAsync(facebook.getSession(), new GraphUserCallback() {
					
					@SuppressLint("DefaultLocale")
					@Override
					public void onCompleted(GraphUser user, Response response) {
						if (user != null) {
							//progress = ProgressDialog.show(CommentActivity.this, "",
								//	getResources().getString(R.string.logining), true);
							String access = facebook.getSession().getAccessToken();
							Date d = facebook.getSession().getExpirationDate();
							long milliseconds = d.getTime();
							SharedPreferences share = getSharedPreferences(
									"sharefilmllk", MODE_PRIVATE);
							SharedPreferences.Editor editor = share
									.edit();

							editor.putLong("access_expires",
									milliseconds);
							editor.putString("access", access);

							String email = (String) user.asMap().get("email");
							String birthday = (String) user.asMap().get("birthday");
							String nickname = (String) user.asMap().get("name");
							String username = (String) user.asMap().get("username");
							editor.putString("username", nickname);
							editor.commit();
							String gender = (String) user.asMap().get("gender");
							if(gender.toLowerCase().equalsIgnoreCase("male")){
								gender = "1";
							}
							else if(gender.toLowerCase().equalsIgnoreCase("female")){
								gender = "0";
							}
							String avatar = (String) user.asMap().get("id");
							avatar = "http://graph.facebook.com/"+avatar+"/picture";
							//String[] params = new String[] {email,username,birthday,nickname,gender,avatar,Config.typeFacebook,"1","gcmid"};//1: facebook
						//	new AsyntaskLoginWithSocial().execute(params);
							publishFeedDialog(null);
						}
					}
				});
			}
			
			@Override
			public void onCancel() {
				
			}
		});*/
	}
	
	private void publishFeedDialog(Object object) {
		Bundle params = new Bundle();
		String url1 = getResources().getString(R.string.urldownloadapp);
		url1 = url1.replace(" ", "%20");
	    params.putString("name", v.getTitle());
	    params.putString("caption", v.getTitle()); 
	    params.putString("description", "Time: " + v.getDuration()+" - "+v.getViews()+" "+getResources().getString(R.string.views)+", "+v.getLikes()+" "+getResources().getString(R.string.likes));  
	    params.putString("link", v.getPlayer_default());
	   // params.putString("link", url);
	    Log.d("log",url1);
	    params.putString("picture", v.getLink()); 
	    @SuppressWarnings("deprecation")
		WebDialog feedDialog = (
	        new WebDialog.FeedDialogBuilder(SearchActiviy.this,
	        		facebook.getSession(),
	            params))
	        .setOnCompleteListener(new OnCompleteListener() {

	            @Override
	            public void onComplete(Bundle values,
	                FacebookException error) {
	                if (error == null) {
	                    // When the story is posted, echo the success
	                    // and the post Id.
	                    final String postId = values.getString("post_id");
	                    if (postId != null) {
	                        Toast.makeText(SearchActiviy.this,
	                        		v.getTitle() +" is shared",
	                            Toast.LENGTH_SHORT).show();
	                    }
	                    
	                }	                
	            }

	        })
	        .build();
	    feedDialog.show();
	}
	ImageButton btnSearch;
	ListView lv;
	EditText et; 
	ProgressBar waiting;
	int page = 1;
	private View footer;
	AdapterSearchVideo adapter; 
	String keyWord = "";
	AsynSearch asynSearch;
	private int mSelectedRow = 0;
	QuickAction mQuickAction;
	private ProgressDialog progress;
	private Handler handler = new Handler();
	private Video v;
	LinearLayout root;
	private AsyncFacebookRunner mAsyncRunner;
	private static final String[] PERMS = new String[] { "read_stream" ,"offline_access"};
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_activity);
/*
		AdView mAdView = (AdView) this.findViewById(R.id.adView);
	    AdRequest adRequest = new AdRequest.Builder().build();
	    mAdView.loadAd(adRequest);
	    */
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(false);
		// mActionBar.setLogo(new ColorDrawable(Color.TRANSPARENT));
		mActionBar.setDisplayUseLogoEnabled(true);
		mActionBar.setHomeButtonEnabled(true);
		mActionBar.setTitle(getResources().getString(R.string.search));
		mActionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_actionbar));
		facebook = new Facebook(getResources().getString(R.string.facebook_app_id));
		mAsyncRunner = new AsyncFacebookRunner(facebook);
		
		btnSearch = (ImageButton) findViewById(R.id.btnsearch);
		et = (EditText) findViewById(R.id.edtsearch);
		lv = (ListView) findViewById(R.id.listViewSearch);
		waiting = (ProgressBar) findViewById(R.id.progressBarWaitingSearch);
		waiting.setVisibility(View.GONE);
		footer = getLayoutInflater().inflate(R.layout.footervideo, null);
		footer.setVisibility(View.INVISIBLE);
		root = (LinearLayout) findViewById(R.id.rootsearch_video);
		lv = (ListView) findViewById(R.id.listViewSearch);		
		lv.addFooterView(footer);   
		adapter = new AdapterSearchVideo(SearchActiviy.this, new ArrayList<Video>());
		lv.setAdapter(adapter);
		lv.setOnScrollListener(new EndlessScrollListener());
		
		btnSearch.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				keyWord = et.getText().toString();
				if(keyWord.equalsIgnoreCase("")){//
					Utility.ShowAlert(SearchActiviy.this, getResources().getString(R.string.error), getResources().getString(R.string.error_message_empty_search));					
				}
				else{
					page = 1;
					Utility.HideKeyboard(et, getApplicationContext());
					adapter.films.clear();
					adapter.notifyDataSetChanged();
					asynSearch = new AsynSearch();
					asynSearch.execute();
				}
			}
		});
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				try {
					Video v = (Video) adapter.getItem(pos);
					if(v!=null){
						String url = v.getPlayer_mobile(); 
						if(url.length()<=6){
							url = v.getPlayer_default();
							url = url.substring(url.indexOf("v=")+2, url.lastIndexOf("&feature"));
						}
						else{
							url = url.substring(url.lastIndexOf("v=")+2);
						}
						if(MainActivity.hmUrl.containsKey(url) ){
							Intent intent = new Intent(SearchActiviy.this, VideoViewBuffer.class);
							intent.putExtra("ID",  MainActivity.hmUrl.get(url));
							intent.putExtra("videoID",  url);
							intent.putExtra("IDInt",  v.getId()+"");
							intent.putExtra("title",  v.getTitle());
							intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
							startActivity(intent);
							overridePendingTransition(R.anim.in, R.anim.out);
						}
						else{
							new AsynGetLinkYouTube().execute(new String[]{url, v.getId()+"",v.getTitle()});
						}
					}
				} catch (Exception e) {
				}
			} 
		});
		//
		//quick action
		 ActionItem addItem 		= new ActionItem(Config.ID_LIKE, getResources().getString(R.string.Likes), getResources().getDrawable(R.drawable.like));
			ActionItem acceptItem 	= new ActionItem(Config.ID_COMMENT, getResources().getString(R.string.comment), getResources().getDrawable(R.drawable.comment));
			ActionItem shareItem 	= new ActionItem(Config.ID_SHARE, getResources().getString(R.string.share), getResources().getDrawable(R.drawable.share_fb));
	         
			mQuickAction 	= new QuickAction(this);
			
			mQuickAction.addActionItem(addItem);
			mQuickAction.addActionItem(acceptItem);
			mQuickAction.addActionItem(shareItem);
			//setup the action item click listener
			mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
				

				@Override
				public void onItemClick(QuickAction quickAction, int pos, int actionId) {
					ActionItem actionItem = quickAction.getActionItem(pos);
					
					if (actionId == Config.ID_LIKE) { //Add item selected
						//Toast.makeText(getApplicationContext(), "Add item selected on row " + mSelectedRow, Toast.LENGTH_SHORT).show();
						User user = new Database(getApplicationContext()).getUser();
						if(user==null){							
								new AlertDialog.Builder(SearchActiviy.this)
								.setTitle(getResources().getString(R.string.buttonlogin))
								.setMessage(getResources().getString(R.string.messagelogintoliked))
								.setNegativeButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										Intent i = new Intent(SearchActiviy.this, LoginActivity.class);
										startActivityForResult(i, Config.LIKE_TO_LOGIN);
									}
								})
								.setPositiveButton(SearchActiviy.this.getResources().getString(R.string.cancel),
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int which) {
											}
								}).show();
							
						}else{						
							likeVideo();					
						}
					}
					else if (actionId == Config.ID_COMMENT) { //Add item selected
						//Toast.makeText(getApplicationContext(), "Add item selected on row " + mSelectedRow, Toast.LENGTH_SHORT).show();
						Intent i = new Intent(getApplicationContext(), CommentActivity.class);
						Video v = (Video) adapter.getItem(mSelectedRow);
						i.putExtra("videoID", v.getVideoID()+"");
						i.putExtra("imageID", v.getLink());
						i.putExtra("title", v.getTitle());
						i.putExtra("ID", v.getId()+"");
						i.putExtra("player_default", v.getPlayer_default());
						i.putExtra("player_mobile", v.getPlayer_mobile());
						i.putExtra("desc", "Time: " + v.getDuration()+" - "+v.getViews()+" "+getResources().getString(R.string.views)+", "+v.getLikes()+" "+getResources().getString(R.string.likes));
						startActivity(i);
					}
					else if (actionId == Config.ID_SHARE) { //Add item selected
						User u = new Database(SearchActiviy.this).getUser();
						v = (Video) adapter.getItem(mSelectedRow);
						//if(u!=null && u.getType().equalsIgnoreCase(Config.typeFacebook))
						{				
							SharedPreferences share = getSharedPreferences("sharefilmllk",
								      MODE_PRIVATE);
								    SharedPreferences.Editor editor = share.edit();
								   
							//SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(DetailChartActivity.this);
							facebook.setAccessToken(share.getString("access", "0"));
							long expied = share.getLong("access_expires", 0);
							facebook.setAccessExpires(expied);
							 
							if(facebook.getSession()!=null){ 
								
								if(v!=null){
								AlertDialog.Builder alert = new AlertDialog.Builder(SearchActiviy.this);
								alert.setTitle(v.getTitle());
								alert.setMessage(getResources().getString(R.string.shareinfordwithfacebook)+" "+share.getString("username", ""));
								alert.setNeutralButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										publishFeedDialog(null);
									}
								});
								alert.setPositiveButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
									}
								});
								alert.setNegativeButton(getResources().getString(R.string.another_account_fb), new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										loginFacebook();
									}
								});
								alert.show();	
								}
							}
							else{
								loginFacebook();
							}
						}
					}
				} 
			});
			
			//setup on dismiss listener, set the icon back to normal
			mQuickAction.setOnDismissListener(new PopupWindow.OnDismissListener() {			
				@Override
				public void onDismiss() {
					adapter.resetButtonDetail();
				}
			});
			//ads
			/*handler.post(new Runnable() {
				
				@Override
				public void run() {
					StartAppAd.init(SearchActiviy.this, Config.devIDStartApp, Config.appIDStartApp); 
					StartAppSearch.init(SearchActiviy.this, Config.devIDStartApp, Config.appIDStartApp);
					StartAppSearch.showSearchBox(SearchActiviy.this); 
					
				}
			}); */

	}
	/*private StartAppAd startAppAd = new StartAppAd(this); 
	@Override 
	public void onResume(){ 
	      super.onResume(); 
	      startAppAd.onResume(); 
	  } 
	@Override 
	  public void onPause() { 
	      super.onPause(); 
	      startAppAd.onPause(); 
	  } 
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if(keyCode==KeyEvent.KEYCODE_HOME){
			 startAppAd.showAd(); 
			    startAppAd.loadAd(); 
		}
		return super.onKeyDown(keyCode, event);
	}*/
	
	class AsynGetLinkYouTube extends AsyncTask<String, Void, String>
	{
		String videoID;
		String ID;
		String title;
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();			
			progress = ProgressDialog.show(SearchActiviy.this, "",
					getResources().getString(R.string.loading), true);	
		}
		@Override
		protected String doInBackground(String... params) {
			this.videoID = params[0];
			this.ID = params[1];
			this.title = params[2];
			return JsonParse.getInstance().getVideoLink(getApplicationContext(), params[0]);
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progress.dismiss();
			try {
				JSONObject json = new JSONObject(result);
					String url = json.getString(Config.result);
					  
					if(url.equalsIgnoreCase("&&signature=")){
						new AsynRemoveVideo().execute(new String[]{this.ID});
						Utility.ShowAlert(SearchActiviy.this, getResources().getString(R.string.error), getResources().getString(R.string.error_canot_play));
						adapter.removeVideo(this.ID);
					}
					else{
						MainActivity.hmUrl.put(this.videoID, url);
						Intent intent = new Intent(SearchActiviy.this, VideoViewBuffer.class);
						intent.putExtra("ID",  url);
						intent.putExtra("videoID",  this.videoID);
						intent.putExtra("IDInt",  this.ID);
						intent.putExtra("title", this.title);
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
						startActivity(intent);
						overridePendingTransition(R.anim.in, R.anim.out);
					}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	class AsynRemoveVideo extends AsyncTask<String, Void, Void>
	{

		@Override
		protected Void doInBackground(String... params) {
			JsonParse.getInstance().removeVideo(getApplicationContext(), params[0]);
			return null;
		}
		
	}
	private void likeVideo(){
		String[] a = {((Video)adapter.getItem(mSelectedRow)).getVideoID()+"","1"};
		new AsynLike().execute(a);
		progress = ProgressDialog.show(SearchActiviy.this, "",
				getResources().getString(R.string.sending), true);
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				if(progress.isShowing()){
					progress.dismiss();
				}
			}
		}, 1000);
	}
	private class AsynLike extends AsyncTask<String, Void, String>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		} 
		@Override
		protected String doInBackground(String... params) {
			User u = new Database(getApplicationContext()).getUser();
			if(u!=null){
				return JsonParse.getInstance().IncreaLike(params[0],params[1],u.getUserId());
			}
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				if(result.equalsIgnoreCase("busy")){
					AlertDialog.Builder alert = new AlertDialog.Builder(SearchActiviy.this);
					alert.setTitle("");
					alert.setMessage(getResources().getString(R.string.notresponse));
					alert.setNeutralButton(getResources().getString(R.string.notresponse_tryagainlater), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Config.isShowingServerBusy = false;
						}
					});
					alert.setPositiveButton(getResources().getString(R.string.notresponse_existapp), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent i = new Intent(SearchActiviy.this, MainActivity.class);
							i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							i.putExtra("exit", "exit");
							startActivity(i);
						}
					});
					if(!Config.isShowingServerBusy){
						alert.show();
						Config.isShowingServerBusy = true;
					}
				}else{
				JSONObject json = new JSONObject(result);
				Video v = (Video) adapter.getItem(mSelectedRow);
				if(json.getString("result").equalsIgnoreCase("1")){
					
					if(v!=null)
					Toast.makeText(SearchActiviy.this, getResources().getString(R.string.alert_successful_like)+" "+v.getTitle(), Toast.LENGTH_LONG).show();		
				}
				else{
					if(v!=null)
						Toast.makeText(SearchActiviy.this, getResources().getString(R.string.alert_successful_like)+" "+v.getTitle(), Toast.LENGTH_LONG).show();
				}
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();
			}
		}
	}
	private boolean loading = false;
	public class EndlessScrollListener implements OnScrollListener {

		private int visibleThreshold;
		private int previousTotal;

		public EndlessScrollListener() {
			visibleThreshold = 1;
			previousTotal = 0;
		}
 
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (loading) {
				if (totalItemCount > previousTotal) {
					loading = false;
					previousTotal = totalItemCount;			
				}
			}
			if (!loading
					&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
				if(adapter!=null && adapter.getCount()>0 && asynSearch!=null && asynSearch.getStatus()==AsyncTask.Status.FINISHED){
					asynSearch = new AsynSearch();
					asynSearch.execute();
				}
				loading = true;
			}			
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

	}
	private class AsynSearch extends AsyncTask<Void, Void, String>
	{
		ArrayList<Video> videos = new ArrayList<Video>();
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			btnSearch.setEnabled(false);
			if(adapter.getCount()==0){
				waiting.setVisibility(View.VISIBLE);
				footer.setVisibility(View.INVISIBLE);
			}
			else{
				waiting.setVisibility(View.INVISIBLE);
				footer.setVisibility(View.VISIBLE);
			}
		}
		@Override
		protected String doInBackground(Void... params) {
			return JsonParse.getInstance().searchVideo(getApplicationContext(), keyWord, page++);
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				if(result.equalsIgnoreCase("busy")){ 
					page--;
					AlertDialog.Builder alert = new AlertDialog.Builder(SearchActiviy.this);
					alert.setTitle("");
					alert.setMessage(getResources().getString(R.string.notresponse));
					alert.setNeutralButton(getResources().getString(R.string.notresponse_tryagain), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
Config.isShowingServerBusy = false;
							asynSearch = new AsynSearch();
							asynSearch.execute();
						}
					});
					alert.setPositiveButton(getResources().getString(R.string.notresponse_existapp), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent i = new Intent(SearchActiviy.this, MainActivity.class);
							i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							i.putExtra("exit", "exit");
							startActivity(i);
						}
					});
					if(!Config.isShowingServerBusy){
						alert.show();
						Config.isShowingServerBusy = true;
					}
				}
				else{
					JSONObject json = new JSONObject(result);
					if(!json.getString(Config.result).equalsIgnoreCase(Config.norow)){
						JSONArray arr = json.getJSONArray(Config.result);
						for(int i=0;i<arr.length();i++){
							JSONObject obj = arr.getJSONObject(i);
							int id = Integer.parseInt(obj.getString(Video.KEY_ID));
							int videoID = Integer.parseInt(obj.getString(Video.KEY_videoID));
							String title = obj.getString(Video.KEY_title);
							String link = obj.getString(Video.KEY_link);
							String playerDefault = obj.getString(Video.KEY_playerDefault);
							String playerMobile = obj.getString(Video.KEY_playerMobile);
							String duration = obj.getString(Video.KEY_duration);
							String likes = obj.getString(Video.KEY_likes);
							String views = obj.getString(Video.KEY_Views);
							
							Video v = new Video(id, videoID, title, link, playerDefault, playerMobile, duration, likes, views);
							videos.add(v);
						}						
						adapter.updateVideo(videos);						
					}
					else if(adapter.getCount()==0){
						if( myAlertDialog != null && myAlertDialog.isShowing() ) return;
						AlertDialog.Builder alert = new AlertDialog.Builder(SearchActiviy.this);
						alert.setTitle("");
						alert.setMessage(getResources().getString(R.string.no_result));
						alert.setNeutralButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								setEditTextFocus(et, true);
							}
						});
						 myAlertDialog = alert.create();
					        myAlertDialog.show();
					}
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();			 
			}
			loading = false;
			waiting.setVisibility(View.INVISIBLE);
			footer.setVisibility(View.INVISIBLE);
			btnSearch.setEnabled(true);
		}
		
	}
	public AlertDialog myAlertDialog;
	public void setEditTextFocus(EditText et, boolean isFocused)
	{
		et.setCursorVisible(isFocused);
		et.setFocusable(isFocused);
		et.setFocusableInTouchMode(isFocused);

	    if (isFocused) 
	    {
	    	et.requestFocus();
	    }
	    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
	}
	@Override
	public void onClickItemVideo(int position, View v) {
		mSelectedRow = position; //set the selected row				
		mQuickAction.getActionItem(0).setTitle(((Video)adapter.getItem(position)).getLikes()+" "+getResources().getString(R.string.likes));
		mQuickAction.show(v);
	}
}
